import os
import shutil
import glob
import re
from datetime import datetime

def copy_files():
    """复制copy文件夹下的log和GIF文件到results文件夹下的时间戳子文件夹"""
    # 获取当前目录（假设脚本在项目根目录运行）
    base_dir = os.path.abspath(os.path.dirname(__file__))
    copy_dir = os.path.join(base_dir, 'copy')
    results_dir = os.path.join(base_dir, 'results')
    
    # 创建带时间戳的子文件夹
    timestamp = datetime.now().strftime('%Y%m%d%H%M')
    results_subdir = os.path.join(results_dir, f'results-{timestamp}')
    
    # 确保results文件夹和时间戳子文件夹存在
    if not os.path.exists(results_dir):
        os.makedirs(results_dir)
        print(f"创建results文件夹: {results_dir}")
    if not os.path.exists(results_subdir):
        os.makedirs(results_subdir)
        print(f"创建时间戳子文件夹: {results_subdir}")
    
    # 查找所有符合格式的子文件夹
    scenario_dirs = []
    for item in os.listdir(copy_dir):
        item_path = os.path.join(copy_dir, item)
        if os.path.isdir(item_path) and item.startswith('Scenario-'):
            scenario_dirs.append(item_path)
    
    print(f"找到 {len(scenario_dirs)} 个场景文件夹")
    
    # 处理每个场景文件夹
    for scenario_dir in scenario_dirs:
        scenario_name = os.path.basename(scenario_dir)
        print(f"处理场景: {scenario_name}")
        
        # 1. 复制main_print.log
        file = os.path.join(scenario_dir, 'main_print.log')
        if os.path.exists(file):
            target_file = os.path.join(results_subdir, scenario_name + '_' + 'main_print.log')
            try:
                shutil.copy2(file, target_file)
                print(f"已复制log文件: {target_file}")
            except Exception as e:
                print(f"复制log文件失败: {e}")
        
        # 2. 复制GIF文件
        # 尝试从文件夹名获取图像文件夹的名称部分
        match = re.match(r'Scenario-(.*)', scenario_name)
        if match:
            image_folder_name = f"image_{match.group(1)}"
            image_folder_path = os.path.join(scenario_dir, 'onsite_images_saved', image_folder_name)
            
            if os.path.exists(image_folder_path):
                # 查找所有GIF文件
                files = glob.glob(os.path.join(image_folder_path, '*.gif'))
                
                for file in files:
                    original_filename = os.path.basename(file)
                    target_file = os.path.join(results_subdir, scenario_name + '_' + original_filename)
                    try:
                        shutil.copy2(file, target_file)
                        print(f"已复制GIF文件: {target_file}")
                    except Exception as e:
                        print(f"复制GIF文件失败: {e}")
            else:
                print(f"未找到图像文件夹: {image_folder_path}")

        # 3.复制 output/plot 到 results_subdir/plot，并合并同名子文件夹
        image_folder_path = os.path.join(scenario_dir, 'outputs', 'plot')
        
        if os.path.exists(image_folder_path):
            # 查找所有PNG文件
            files = glob.glob(os.path.join(image_folder_path, '*.png'))
            
            for file in files:
                original_filename = os.path.basename(file)
                target_file = os.path.join(results_subdir, scenario_name + '_' + original_filename)
                try:
                    shutil.copy2(file, target_file)
                    print(f"已复制PNG文件: {target_file}")
                except Exception as e:
                    print(f"复制PNG文件失败: {e}")
        else:
            print(f"未找到图像文件夹: {image_folder_path}")

        # 4.复制 output/*csv 到 results_subdir/csv，并合并同名子文件夹
        folder_path = os.path.join(scenario_dir, 'outputs')
        folder_path1 = os.path.join(scenario_dir, 'planner', 'all_results', 'path_spd_saved')
        if os.path.exists(folder_path):
            # 查找所有CSV文件
            files = glob.glob(os.path.join(folder_path, '*.csv'))
            
            for file in files:
                original_filename = os.path.basename(file)
                target_file = os.path.join(results_subdir, 'csv', original_filename)
                os.makedirs(os.path.dirname(target_file), exist_ok=True)
                try:
                    shutil.copy2(file, target_file)
                    print(f"已复制CSV文件: {target_file}")
                except Exception as e:
                    print(f"复制CSV文件失败: {e}")
                folder_path = os.path.join(scenario_dir, 'outputs')
        
        # if os.path.exists(folder_path1):
        #     # 查找所有CSV文件
        #     files = glob.glob(os.path.join(folder_path1, '*.npz'))
            
        #     for file in files:
        #         original_filename = os.path.basename(file)
        #         target_file = os.path.join(results_subdir, 'npz', original_filename)
        #         os.makedirs(os.path.dirname(target_file), exist_ok=True)
        #         try:
        #             shutil.copy2(file, target_file)
        #             print(f"已复制npz文件: {target_file}")
        #         except Exception as e:
        #             print(f"复制npz文件失败: {e}")
        else:
            print(f"未找到npz文件夹: {folder_path1}")

if __name__ == "__main__":
    copy_files() 